import { postAlbumPage } from '@/services/cms/14516';
import { defaultSearchParams } from '@/services/global/base';
import { Select } from 'antd';
import { debounce } from 'lodash';
import { useEffect, useState } from 'react';

const { Option } = Select;

type Props = {
  form: any;
  value?: string;
  onChange?: (value: string) => void;
  setSelectAlbum?: (arg: any) => void;
};

const SelectAlbumList: React.FC<Props> = ({ value, onChange, setSelectAlbum }) => {
  const [data, setData] = useState<any[]>([]);

  const handleSearch = (searchValue: string) => {
    if (searchValue === '') {
      setData([]);
      return;
    }

    const params = { filters: { keyWord: searchValue } };
    debounce(async () => {
      const res = await postAlbumPage({ ...defaultSearchParams, ...params });
      setData(res.data ? res.data.list : []);
    }, 500)();
  };

  useEffect(() => {
    handleSearch(value || '');
  }, []);

  const handleChange = (ret: string) => {
    if (onChange) {
      onChange(ret);
    }
    if (setSelectAlbum) {
      setSelectAlbum(data.find((item) => item.albumId === ret));
    }
  };

  const options = data.map((d) => (
    <Option key={d.albumId} value={d.albumId}>
      <span>{`${d.albumName}(${d.albumId})`}</span>
    </Option>
  ));

  return (
    <Select
      showSearch
      value={value}
      placeholder="输入专辑ID或名字搜索"
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={null}
    >
      {options}
    </Select>
  );
};

export default SelectAlbumList;
